from django.shortcuts import render
from django.core.paginator import Paginator
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from article.models import Article
from django.core.mail import send_mail
from django.conf import settings
from .models import User, Record, Comments
from django.core.cache import cache  # 导入 Django 的缓存模块
from datetime import timedelta

import random
import hashlib
import os
import json
import jieba
import logging

jieba.setLogLevel(logging.INFO)


def index_1(request):
    """
    首页
    :return:
    """
    pass

    html = """
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>社交媒体帖子效果</title>
    <style>

        body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    margin: 0;
    padding: 20px;
    line-height: 1.6;
}

.container {
    max-width: 800px;
    margin: 0 auto;
}

.post {
    background-color: white;
    border: 1px solid #e1e8ed;
    border-radius: 8px;
    margin-bottom: 20px;
    padding: 15px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.post-header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.avatar {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 10px;
}

.user-info h3 {
    margin: 0;
    font-size: 16px;
    color: #1a73e8;
}

.user-info .time {
    font-size: 12px;
    color: #666;
}

.post-content {
    font-size: 14px;
    color: #333;
}

.post-content p {
    margin: 0 0 10px;
}

.post-actions {
    font-size: 12px;
    color: #666;
    display: flex;
    gap: 15px;
}

.post-actions span {
    margin-right: 10px;
}

.comments::before { content: "评论: "; }
.likes::before { content: "点赞: "; }
.views::before { content: "查看: "; }
    </style>
</head>
<body>
"""

    footer = """
    </body>
</html>
    """

    # container = """
    #
    #    <div class="container">
    #        <!-- 帖子 1：10亿数据，如何优化？ -->
    #
    #
    #        <!-- 帖子 2：分布式备份算法优化的问题 -->
    #        <div class="post">
    #            <div class="post-header">
    #                <img src="https://via.placeholder.com/50" alt="用户头像" class="avatar">
    #                <div class="user-info">
    #                    <h3>Ofnoname</h3>
    #                    <span class="time">2025-02-21 17:41</span>
    #                </div>
    #            </div>
    #            <div class="post-content">
    #                <p>分布式备份算法问题如何优化：性能考虑分层的存储效果直观优化后的部署用户，接入用户的王牌候选者查询算法综合优化架构。985硕士还在担忧工作面 复杂的对象发生，创作者强人小姐和美妙系统外支持商品—要素。看你的首座终极符，立即下载吧！——“拓张拓网”学术伴侣“价值存储 你的朋友，你真的上顶级架构《分布式备份》...</p>
    #            </div>
    #            <div class="post-actions">
    #                <span class="comments">0</span>
    #                <span class="likes">3</span>
    #                <span class"views">69</span>
    #            </div>
    #        </div>
    #    </div>
    #
    #    """

    # 查询数据库获取数据
    articles = Article.objects.all()

    container = "<div class='container'>"
    for article in articles:
        container += f"""
         <div class="post">
               <div class="post-header">
                   
                   <div class="user-info">
                       <h3>{article.title}</h3>
                       <span class="time">2025-02-21 19:58</span>
                   </div>
               </div>
               <div class="post-content">
                   <p>{article.description}</p>
               </div>
               <div class="post-actions">
                   <span class="comments">0</span>
                   <span class="likes">0</span>
                   <span class="views">12</span>
               </div>
           </div>
        """

    container += "</div>"

    html = html + container + footer
    return HttpResponse(html)


def index(request):
    # --- 缓存逻辑开始 ---
    # 1. 尝试从缓存中获取热门文章
    top5 = cache.get('top5_articles')
    if top5 is None:
        # 缓存中没有，就去查数据库
        print("从数据库查询热门文章...")
        top5 = Article.objects.order_by("-views")[:5]
        # 将查询结果存入缓存，设置过期时间为 15 分钟 (900秒)
        cache.set('top5_articles', top5, 60 * 15)
    else:
        print("从 Redis 缓存中读取热门文章...")
    # --- 缓存逻辑结束 ---

    page = request.GET.get("page", 1)
    articles = Article.objects.order_by("-id")
    paginator = Paginator(articles, 4)
    articles_page = paginator.page(page)

    context = {
        "articles": articles_page,
        "title": "小淘宝博客网",
        "top5": top5  # 使用从缓存或数据库中获取的 top5 数据
    }
    return render(request, "index.html", context=context)


def detail_asdffasdf(request):
    return render(request, "detail.html")


def detail(request, a_id):


    article = Article.objects.get(id=a_id)
    article.views += 1
    article.save()  # 更新文章的浏览量
    context = {
        "article": article
    }

    # 获取文章的所有评论
    comments = Comments.objects.filter(article=article)
    context["comments"] = comments
    return render(request, "detail.html", context=context)


def register(request):
    """
    用户注册
    :param request:
    :return:
    """
    method = request.method  # 获取请求的方法
    if method == "GET":
        return render(request, "register.html")
    else:
        # 获取提交的数据
        username = request.POST["username"]  # 获取用户名
        password = request.POST["password"]  # 获取密码
        c_password = request.POST["c_password"]  # 获取确认密码
        email = request.POST["email"]  # 获取邮箱
        email_code = request.POST["email_code"]  # 获取邮箱验证码

        """
        验证邮箱验证码是否正确
        """
        code = request.session.get("email_code", None)  # 从session中获取邮箱验证码
        if email_code != code:
            message = "邮箱验证错误，请输入正确的验证码"
            context = {
                "message": message,
                "return_url": "/register",
                "return": "返回到注册页面"
            }
            return render(request, "error.html", context=context)

        """
        验证用户名
        """
        try:
            user = User.objectes.get(username=username)
            message = "用户名称已经存在，请更换用户名"
            context = {
                "message": message,
                "return_url": "/register",
                "return": "返回到注册页面"
            }
            return render(request, "error.html", context=context)

        except Exception:
            pass

        """
        确认密码和确认密码是否相等
        """

        """
        将用户提交的数据存储到数据库里面
        """
        # 密码使用md5加密
        cipher_text = hashlib.md5(password.encode("utf-8")).hexdigest()
        User.objects.create(
            username=username,
            email=email,
            password=cipher_text
        )

        message = "恭喜你，注册成功!"
        context = {
            "message": message,
            "return_url": "/login",
            "return": "跳转到登录界面"
        }

        return render(request, "success.html", context=context)


def login(request):
    """
    登录界面
    :param request:
    :return:
    """

    method = request.method  # 获取请求的方法
    if method == "GET":
        return render(request, "login.html")
    else:
        username = request.POST["username"]  # 获取用户名
        password = request.POST["password"]  # 获取密码

        # 判断用户名是否已经存在
        try:
            user = User.objects.get(username=username)

            # 判断密码是否正确
            cipher_text = hashlib.md5(password.encode("utf-8")).hexdigest()
            if cipher_text == user.password:
                """
                        1、生成一个唯一的字符串
                        2、我把这个唯一的字符串写入cookie中
                        3、用这个唯一的字符串来在服务端创建一个文件
                        4、把用户信息存入文件中
                """
                import time

                # timestamp = str(time.time())  # 用时间戳来进行加密
                # session_id = hashlib.md5(timestamp.encode("utf-8")).hexdigest()
                # filename = session_id + ".txt"
                # file_path = os.path.join(settings.BASE_DIR, "session", filename)
                # with open(file_path, "w", encoding="utf-8") as fp:
                #     info = json.dumps({"username": username})
                #     fp.write(info)

                message = "登录成功!"
                context = {
                    "message": message,
                    "return_url": "/",
                    "return": "跳转到首页"
                }
                response = render(request, "success.html", context=context)
                request.session["username"] = username
                return response

            else:
                message = "密码错误，请重新输入!"
                context = {
                    "message": message,
                    "return_url": "/login",
                    "return": "返回到登录界面"
                }

                return render(request, "error.html", context=context)

        except Exception as e:
            message = "用户名不存在!"
            context = {
                "message": message,
                "return_url": "/login",
                "return": "返回到登录界面"
            }

            return render(request, "error.html", context=context)


def logout(request):
    """
    退出
    :param request:
    :return:
    """

    del request.session["username"]
    # 重定向到登录界面
    return HttpResponseRedirect("/")


def send_verification_code(request):
    """
    发送邮件
    :return:
    """

    email = request.POST["email"]
    # 生成一个6位数的验证码
    ver_code = gen_ver_code(6)
    request.session["email_code"] = ver_code  # 将邮箱验证码存储到session中

    # 发送邮件
    send_mail(
        subject="[小小淘宝]邮箱验证码",
        message=f"您的验证码是：{ver_code}",
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[email]
    )

    return JsonResponse({"success": 1, "msg": "发送成功"})


def gen_ver_code(nums):
    """
    生成指定个数验证码
    :param nums:
    :return:
    """
    string = "234g4jak56k5h3g3aomadmfaiwqrr87363asmasejrjqrr247534939mwrweurk35674h"
    max_index = len(string) - 1

    random_str = ""
    for x in range(nums):
        i = random.randint(0, max_index)
        char = string[i]
        random_str += char

    return random_str


def user_center(request):
    """
    用户中心
    :return:
    """
    # 判断是否已经登录
    username = request.session.get("username", None)
    if not username:
        # 用户没有登录
        return HttpResponseRedirect("/login")  # 重定向到登录界面

    articles = Article.objects.filter(author=username)
    article_count = len(articles)  # 文章总数

    total_views = 0  # 总的浏览数
    for article in articles:
        total_views += article.views

    return render(request, "user_center.html",
                  {"articles": articles, "article_count": article_count, "total_views": total_views})


def submit_article(request):
    """
    文章发布
    """
    # 获取数据
    title = request.POST["title"]  # 获取标题
    description = request.POST["description"]  # 获取摘要
    content = request.POST["content"]  # 获取内容

    # 作者
    author = request.session["username"]

    article = Article.objects.create(
        title=title,
        description=description,
        content=content,
        author=author
    )

    return JsonResponse({"code": 0, "msg": "添加成功!", "a_id": article.id})


def test(request):
    """
    测试函数
    """

    # for x in dir(request):
    #     print(x)

    print("请求头：", request.headers, type(request.headers))
    print("是否是Ajax请求：", request.is_ajax())
    print("使用的请求方法是：", request.method)
    print("请求路径：", request.path)
    print("请求协议：", request.scheme)

    # GET
    # print("GET内容: ", request.GET)
    # print("age的值是：",request.GET["age"])

    method = request.method
    if method == "GET":
        html = """
            <form  method="post">
                <input type="text" name="username" placeholder="请输入你的用户名" /><br/>
                <input type="password" name="password" placeholder="请输入你的密码" /><br/>
                <button type="submit">提交</button>
            
            </form>
        
        
        """
    else:
        print(request.POST)
        username = request.POST["username"]  # 获取用户
        password = request.POST["password"]  # 获取密码

        print(username, password)

    return HttpResponse(html)


def test2(request):
    """
    文件上传
    """

    method = request.method
    if method == "GET":
        html = """
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="image" /><br/><br/>
            <button type="submit">上传文件</button>
        </form>
        """

        return HttpResponse(html)
    else:

        image = request.FILES.get("image", None)
        if image:
            # 1、获取文件的名称
            file_name = image.name

            file_path = os.path.join(settings.BASE_DIR, "static", "uploads", file_name)

            # 打开文件
            with open(file_path, "wb") as fp:
                # 获取文件内容
                for chunk in image.chunks():
                    fp.write(chunk)

        return HttpResponse("上传成功")


def test3(request):
    """
    响应：
    1、响应一个html文档(html字符串)
    2、响应一个JSON字符串(通常用于接口请求)
    3、重定向,告诉浏览器去请求一个新的地址(用来做跳转)
    """
    # 响应一个html文档(字符串)
    # html ="""
    #     <div>hello world</div>
    # """
    # return HttpResponse(html)

    # return JsonResponse({"code": 1, "msg": "上传失败"})

    return HttpResponseRedirect("https://www.baidu.com")


def clean_no_key_words(word_list):
    """
    清楚非关键字
    :param word_list:
    :return:
    """
    new_word_list = []
    for word in word_list:
        if word not in settings.NO_KEY_WORDS:
            new_word_list.append(word)

    return new_word_list


def search(request):
    """
    文章搜索
    :return:
    """
    key_word = request.GET["q"]
    words = jieba.cut(key_word, cut_all=False)
    new_words = clean_no_key_words(words)

    """
        判断用户是否登录：
        如果登录了就将用户记录写入表中，
        如果没有登录就不写入
    """
    username = request.session.get("username", None)

    if username:
        user = User.objects.get(username=username)
        Record.objects.create(
            user=user,
            search=key_word
        )

    articles = []
    for word in new_words:
        articles += Article.objects.filter(title__icontains=word).order_by("-views")
    context = {
        "articles": articles,
        "key_word": key_word
    }

    return render(request, "search.html", context=context)


def search_suggest(request):
    """
    搜索建议 python
    :return:
    """
    username = request.session.get("username", None)
    if not username:
        return JsonResponse({"code": 1, "msg": "用户没有登录!"})

    query = request.GET["query"]

    # 获取用户对象
    user = User.objects.get(username=username)

    records = Record.objects.filter(user=user, search__icontains=query)

    new_records = []
    for record in records:
        new_records.append({"search": record.search})

    return JsonResponse({"code": 0, "data": new_records}, safe=False)


def comments(request):
    """
    文章评论
    :param request:
    :return:
    """

    content = request.POST["content"]
    article_id = request.POST["article_id"]

    article = Article.objects.get(id=article_id)

    username = request.session["username"]
    user = User.objects.get(username=username)

    # 添加评论
    comment = Comments.objects.create(
        content=content,
        user=user,
        article=article
    )

    comment_time = comment.comment_time + timedelta(hours=8)

    comment_time = comment_time.strftime("%Y-%m-%d %H:%M:")

    return JsonResponse({"code": 0, "data": {"comment_time": comment_time}})

